﻿using SmartSSO.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Mvc;

namespace SmartSSO.ClientExample2.Controllers
{
   [SSOAuth]
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        public ActionResult LoginOut()
        {
            ViewBag.Message = "LoginOut.";
            if (HttpContext.Request.Cookies[SSOAuthAttribute.SessionKey] != null)
            {
                var cookieSessionkey = HttpContext.Request.Cookies[SSOAuthAttribute.SessionKey].Value;
                var cookieSessionUserName = HttpContext.Request.Cookies[SSOAuthAttribute.SessionUserName].Value;
                string loginOutRet = LoginOut(cookieSessionkey);
                if (loginOutRet.Contains("true"))//登出成功
                {
                    RemoveCookie(HttpContext.Request.Cookies[SSOAuthAttribute.SessionKey].Name);
                    RemoveCookie(HttpContext.Request.Cookies[SSOAuthAttribute.SessionUserName].Name);

                    string loginurl = string.Format("{0}/passport?appkey={1}&username={2}",
                        ConfigurationManager.AppSettings["SSOPassport"],
                        ConfigurationManager.AppSettings["SSOAppKey"], cookieSessionUserName
                        );
                    return Redirect(loginurl);
                }
            }//未登录则跳转到首页
            return View("Index");
        }

        /// <summary>
        /// 删除cookie
        /// </summary>
        /// <param name="cookieName"></param>
        public void RemoveCookie(string cookieName)
        {
            HttpCookie aCookie = new HttpCookie(cookieName);
            aCookie.Expires = DateTime.Now.AddDays(-1);
            HttpContext.Response.Cookies.Add(aCookie);
        }

        /// <summary>
        /// 通过向SSO的webapi请求登出
        /// </summary>
        /// <param name="sessionKey"></param>
        /// <returns></returns>
        private static string LoginOut(string sessionKey)
        {
            var httpClient = new HttpClient
            {
                BaseAddress = new Uri(ConfigurationManager.AppSettings["SSOPassport"])
            };
            var requestUri = string.Format("api/LoginOut?sessionKey={0}", sessionKey);
            try
            {
                var resp = httpClient.GetAsync(requestUri).Result;
                resp.EnsureSuccessStatusCode();
                return resp.Content.ReadAsStringAsync().Result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }




    }
}